// 商品分类管理组件
import { Card, Typography, Input, Select, Button, Form, Row, Col, Space, Table, message, Image, Popconfirm, Modal, Switch } from 'antd';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RedoOutlined } from '@ant-design/icons';
import React, { useState, useCallback, useEffect } from 'react';
import ImageUploader from '@/components/ImageUploader';
import { goodstypeApi, goodstypeAddApi, goodstypeDeleteApi } from '@/api/goodstype/index';
import styles from './index.module.css';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { handleNumberInput, handleTextOnlyInput } from '@/components/business/index';

// 常量定义 
const { Title } = Typography;
const { Option } = Select;

// 分页配置
export const PAGE_SIZE_OPTIONS = ['10', '20', '50'];

// 类型定义 

/**
 * 表格行选择类型
 */
type TableRowSelection<T> = TableProps<T>['rowSelection'];

/**
 * 列表请求参数类型
 */
export interface CategoryListParams {
  current: number;      // 当前页码
  pageSize: number;     // 每页条数
  title?: string;       // 分类名称
  status?: string;      // 状态
  homeview?: string;    // 首页显示
}

/**
 * 商品分类表单数据类型
 */
export interface CategoryFormValues {
  title?: string;       // 分类名称
  img?: string;         // 分类图片
  status?: number;      // 状态：1开启/0关闭
  homeview?: number;    // 首页显示：1显示/0不显示
  sort?: number;        // 排序
  id?: number;          // 编辑时的ID
}

/**
 * 商品分类列表项类型
 */
export interface CategoryItem {
  id: number;           // 分类ID
  title: string;        // 分类名称
  img: string;          // 分类图片
  status: number;       // 状态：1开启/0关闭
  homeview: number;     // 首页显示：1显示/0不显示
  sort: number;         // 排序
  createtime: number;   // 创建时间
  updatetime: number;   // 更新时间
}

/**
 * 接口响应类型
 */
export interface ApiResponse<T = any> {
  code: number;         // 响应码
  data: T;              // 响应数据
  msg?: string;         // 响应消息
}

/**
 * 列表接口响应数据类型
 */
export interface CategoryListResponse {
  list: CategoryItem[]; // 分类列表
  total: number;        // 总条数
}

/**
 * 搜索表单值类型
 */
export interface SearchFormValues {
  title?: string;       // 分类名称
  status?: string;      // 状态
  homeview?: string;    // 首页显示
}

// 组件主体 
const CategoryManagement: React.FC = () => {
  // 状态管理 
  const [searchForm] = Form.useForm<SearchFormValues>();                    // 搜索表单实例
  const [categoryForm] = Form.useForm<CategoryFormValues>();               // 分类表单实例
  
  // 分类列表数据
  const [categoryList, setCategoryList] = useState<CategoryItem[]>([]);
  // 加载状态
  const [loading, setLoading] = useState(false);
  // 分页配置
  const [pagination, setPagination] = useState({
    align: 'center',
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条数据`,
    pageSizeOptions: PAGE_SIZE_OPTIONS,
  });
  // 模态框状态
  const [modalVisible, setModalVisible] = useState(false);                 // 模态框显示状态
  const [submitLoading, setSubmitLoading] = useState(false);              // 提交加载状态
  const [imageUrl, setImageUrl] = useState('');                           // 图片URL
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]); // 选中行keys
  const [currentEditId, setCurrentEditId] = useState<number | null>(null); // 当前编辑ID

  /**
   * 获取分类列表数据
   * @param params 请求参数
   */
  const getCategoryList = async (params?: Partial<CategoryListParams>) => {
    try {
      setLoading(true);

      // 获取搜索表单的值
      const searchValues = searchForm.getFieldsValue();

      // 构建请求参数
      const requestParams: CategoryListParams = {
        current: params?.current || pagination.current,
        pageSize: params?.pageSize || pagination.pageSize,
        ...searchValues
      };
      
      // 过滤掉空值参数
      Object.keys(requestParams).forEach(key => {
        if (requestParams[key as keyof CategoryListParams] === '' || requestParams[key as keyof CategoryListParams] === undefined) {
          delete requestParams[key as keyof CategoryListParams];
        }
      });

      console.log('获取分类列表参数:', requestParams);
      const response = await goodstypeApi().signIn(requestParams);
      const apiResponse = response as ApiResponse<CategoryListResponse>;
      
      if (apiResponse?.code === 1) {
        setCategoryList(apiResponse.data?.list || []);
        setPagination(prev => ({
          ...prev,
          current: requestParams.current,
          pageSize: requestParams.pageSize,
          total: apiResponse.data?.total || 0,
        }));
        console.log('分类列表获取成功');

      } else {
        message.error('获取分类列表失败：' + (apiResponse?.msg || '未知错误'));
        setCategoryList([]);
        setPagination(prev => ({ ...prev, total: 0 }));
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
      message.error('获取分类列表失败');
      setCategoryList([]);
      setPagination(prev => ({ ...prev, total: 0 }));
    } finally {
      setLoading(false);
    }
  };

  /**
   * 删除分类
   * @param ids 要删除的分类ID数组
   */
  const handleDelete = async (ids: React.Key[]) => {
    if (ids.length === 0) return;

    try {
      setLoading(true);
      const response = await goodstypeDeleteApi().signIn({ ids: ids.join(',') });
      const apiResponse = response as ApiResponse;

      if (apiResponse?.code === 1) {
        message.success('删除成功');
        setSelectedRowKeys(prev => prev.filter(key => !ids.includes(key)));
        getCategoryList();
      } else {
        message.error('删除失败：' + (apiResponse?.msg || '未知错误'));
      }
    } catch (error) {
      console.error('删除分类失败:', error);
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  };

  /**
   * 新增/编辑分类
   */
  const handleAddCategory = async () => {
    try {
      const values = await categoryForm.validateFields();
      setSubmitLoading(true);
      
      // 转换表单数据
      const submitData: CategoryFormValues = {
        title: values.title || '',
        img: values.img || '',
        status: values.status || 0,
        homeview: values.homeview || 0,
        sort: values.sort || 0,
        ...(currentEditId && { id: currentEditId })
      };
      
      console.log('提交分类数据:', submitData);
      const response = await goodstypeAddApi().signIn(submitData);
      const apiResponse = response as ApiResponse;

      if (apiResponse?.code === 1) {
        message.success(currentEditId ? '编辑分类成功' : '新增分类成功');
        handleCancelModal();
        getCategoryList();
      } else {
        message.error((currentEditId ? '编辑失败' : '新增失败') + '：' + (apiResponse?.msg || '未知错误'));
      }
    } catch (error: any) {
      console.error('操作分类失败:', error);
      // 错误提示
      if (error.errorFields && error.errorFields.length > 0) {
        const errorMessage = error.errorFields.map((field: any) => field.errors.join(', ')).join('; ');
        message.error(`表单验证失败: ${errorMessage}`);
      } else {
        message.error(currentEditId ? '编辑失败' : '新增失败');
      }
    } finally {
      setSubmitLoading(false);
    }
  };

  // 事件处理函数 

  /**
   * 显示新增分类模态框
   */
  const handleShowModal = () => {
    setModalVisible(true);
    setCurrentEditId(null);
    setImageUrl('');
    // 初始化表单默认值
    categoryForm.setFieldsValue({
      title: '',
      status: 1,
      homeview: 1,
      sort: 0,
      img: '',
    });
  };

  /**
   * 关闭模态框
   */
  const handleCancelModal = () => {
    setModalVisible(false);
    categoryForm.resetFields();
    setImageUrl('');
    setCurrentEditId(null);
  };

  /**
   * 图片上传成功回调
   * @param fullUrl 上传成功的图片URL
   */
  const handleImageUploadSuccess = (fullUrl: string | string[]) => {
    const url = Array.isArray(fullUrl) ? fullUrl[0] : fullUrl;
    setImageUrl(url);
    categoryForm.setFieldsValue({ img: url });
  };

  /**
   * 表格分页切换处理
   * @param newPagination 新的分页配置
   */
  const handleTableChange = (newPagination: any) => {
    const updatedPagination = {
      ...pagination,
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    };

    setPagination(updatedPagination);
    setSelectedRowKeys([]);
    getCategoryList({
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    });
  };

  /**
   * 搜索处理函数
   */
  const handleSearch = async () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    setSelectedRowKeys([]);
    getCategoryList({ current: 1 });
  };

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    setSelectedRowKeys([]);
    getCategoryList({ current: 1 });
  };

  /**
   * 刷新列表
   */
  const handleRefresh = () => {
    setSelectedRowKeys([]);
    getCategoryList();
  };

  /**
   * 编辑按钮点击处理
   * @param record 要编辑的分类数据
   */
  const handleEdit = (record: CategoryItem) => {
    console.log('编辑分类:', record);
    setCurrentEditId(record.id);
    setModalVisible(true);
    setImageUrl(record.img);

    // 填充表单数据
    categoryForm.setFieldsValue({
      title: record.title,
      img: record.img,
      status: record.status,
      homeview: record.homeview,
      sort: record.sort
    });
  };

  /**
   * 搜索框回车键处理函数
   * @param e 键盘事件
   */
  const handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  /**
   * 验证分类名称唯一性
   * @param value 分类名称
   * @param excludeId 排除的ID（编辑时使用）
   * @returns 是否重复
   */
  const checkDuplicateTitle = useCallback((
    value: string,
    excludeId: number | null
  ) => {
    if (!value) return false;
    return categoryList.some(item => item.title === value && item.id !== excludeId);
  }, [categoryList]);

  /**
   * 渲染状态文本
   * @param status 状态值
   * @returns 状态显示组件
   */
  const renderStatus = useCallback((status: number) => {
    const isActive = status === 1;
    return (
      <div className={styles.statusContainer}>
        {isActive && <span className={styles.statusDot} />}
        {isActive ? '开启' : '关闭'}
      </div>
    );
  }, []);

  /**
   * 渲染首页显示文本
   * @param homeview 首页显示状态
   * @returns 首页显示组件
   */
  const renderHomeView = useCallback((homeview: number) => {
    const isShow = homeview === 1;
    return (
      <div className={styles.statusContainer}>
        {isShow && <span className={styles.statusDot} />}
        {isShow ? '显示' : '不显示'}
      </div>
    );
  }, []);

  // 表格配置 
  const columns: ColumnsType<CategoryItem> = [
    {
      title: '序号',
      key: 'index',
      align: 'center',
      width: 50,
      render: (_, __, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '分类名称',
      dataIndex: 'title',
      align: 'center',
      key: 'title',
      width: 120,
    },
    {
      title: '分类图片',
      dataIndex: 'img',
      align: 'center',
      key: 'img',
      width: 120,
      render: (img: string) =>
        img ? (
          <Image
            width={40}
            height={40}
            src={img}
            style={{ objectFit: 'cover', borderRadius: '4px' }}
            preview={{ minScale: 0.5, maxScale: 1.2, scaleStep: 0.1 }}
          />
        ) : (
          '无'
        ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      width: 120,
      render: renderStatus,
    },
    {
      title: '首页显示',
      dataIndex: 'homeview',
      align: 'center',
      key: 'homeview',
      width: 120,
      render: renderHomeView,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      align: 'center',
      width: 120,
      key: 'sort',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      render: (_: any, record: CategoryItem) => (
        <Space size="small">
          <Button
            type="primary"
            icon={<EditOutlined />}
            className={styles.deleteButton}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="是否确认删除？"
            onConfirm={() => handleDelete([record.id])}
            okText="确定"
            cancelText="取消"
            okType="danger"
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              className={styles.deleteButton}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection: TableRowSelection<CategoryItem> = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    columnWidth: 50,
  };

  // 渲染辅助函数 
  
  /**
   * 渲染表格内容
   * @returns 表格内容组件
   */
  const renderTableContent = () => (
    <Card variant="borderless" styles={{ body: { padding: 0 } }}>
      <div className={styles.tabContent}>
        <div className={styles.actionBar}>
          <div className={styles.actionButtons}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                className={styles.deleteButton}
                onClick={handleShowModal}
              >
                新建
              </Button>
            </Space>
          </div>
          <div className={styles.refreshIcon}>
            <RedoOutlined
              style={{ fontSize: '18px', cursor: 'pointer' }}
              className={loading ? styles.refreshing : ''}
              title="刷新页面"
              onClick={handleRefresh}
            />
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={categoryList}
          rowKey="id"
          loading={loading}
          className={styles.customTable}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
          rowSelection={rowSelection}
        />
      </div>
    </Card>
  );

  // 副作用 
  useEffect(() => {
    getCategoryList();
  }, []); // 仅初始化时加载一次

  // 组件渲染 
  return (
    <div className={styles.pageWrapper}>
      <Title level={4} className={styles.pageTitle}>商品分类</Title>

      {/* 搜索表单区域 */}
      <div className={styles.formContainer}>
        <Form
          form={searchForm}
          layout="horizontal"
          colon={true}
          labelAlign="left"
          className={styles.formLeft}
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 17 }}
        >
          <Row gutter={[24, 16]} style={{ width: '100%', marginBottom: 16 }}>
            {/* 分类名称搜索 */}
            <Col span={8}>
              <Form.Item
                name="title"
                label="分类名称"
                style={{ margin: 0 }}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Input
                  placeholder="请输入分类名称"
                  onPressEnter={handleInputKeyPress}
                  className={styles.formInput}
                />
              </Form.Item>
            </Col>

            {/* 分类状态搜索 */}
            <Col span={8}>
              <Form.Item
                name="status"
                label="分类状态"
                style={{ margin: 0 }}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Select
                  placeholder="请选择状态"
                  className={styles.formSelect}
                  allowClear
                  onClick={handleSearch}
                  onClear={handleSearch}
                  style={{ width: '100%' }}
                >
                  <Option value="1">开启</Option>
                  <Option value="0">关闭</Option>
                </Select>
              </Form.Item>
            </Col>

            {/* 首页显示搜索 */}
            <Col span={8}>
              <Form.Item
                name="homeview"
                label="首页显示"
                style={{ margin: 0 }}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Select
                  placeholder="请选择显示状态"
                  className={styles.formSelect}
                  allowClear
                  onClick={handleSearch}
                  onClear={handleSearch}
                  style={{ width: '100%' }}
                >
                  <Option value="1">显示</Option>
                  <Option value="0">不显示</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        {/* 操作按钮区域 */}
        <div className={styles.formRight}>
          <Button
            type="primary"
            icon={<SearchOutlined />}
            className={styles.deleteButton}
            onClick={handleSearch}
            style={{ marginBottom: 8 }}
          >
            查询
          </Button>
          <Button
            icon={<ReloadOutlined />}
            className={styles.deleteButton}
            onClick={handleReset}
          >
            重置
          </Button>
        </div>
      </div>

      {/* 渲染表格内容 */}
      {renderTableContent()}

      {/* 新增/编辑商品分类模态框 */}
      <Modal
        title={currentEditId ? '编辑商品分类' : '新建商品分类'}
        open={modalVisible}
        onCancel={handleCancelModal}
        centered
        style={{ maxWidth: 400 }}
        footer={[
          <Button key="cancel" onClick={handleCancelModal}>取消</Button>,
          <Button key="submit" type="primary" loading={submitLoading} onClick={handleAddCategory}>
            确定
          </Button>,
        ]}
        maskClosable={false}
      >
        <Form
          form={categoryForm}
          layout="horizontal"
          labelCol={{ span: 6 }}
          labelAlign="left"
          wrapperCol={{ span: 18 }}
        >
          {/* 分类名称表单项 */}
          <Form.Item<CategoryFormValues>
            name="title"
            label="分类名称"
            rules={[
              { required: true, message: '请输入分类名称' },
              { max: 50, message: '分类名称不能超过50个字符' },
              {
                validator: async (_, value) => {
                  if (value && checkDuplicateTitle(value, currentEditId)) {
                    throw new Error('该分类名称已存在，请更换');
                  }
                },
                validateTrigger: ['change', 'blur'],
              },
            ]}
          >
            <Input
              placeholder="请输入分类名称"
              maxLength={50}
              onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleTextOnlyInput(categoryForm, 'title', e, { maxLength: 50 })
              }
              onBlur={(e: React.FocusEvent<HTMLInputElement>) =>
                handleTextOnlyInput(categoryForm, 'title', e as any, { maxLength: 50 })
              }
            />
          </Form.Item>
          
          {/* 状态表单项 */}
          <Form.Item<CategoryFormValues>
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            valuePropName="checked"
          >
            <Switch
              checkedChildren="显示"
              unCheckedChildren="不显示"
            />
          </Form.Item>
          
          {/* 分类图片表单项 */}
          <Form.Item<CategoryFormValues>
            name="img"
            label="分类图片"
            rules={[{ required: true, message: '请上传分类图片' }]}
          >
            <ImageUploader
              key={imageUrl}
              imageUrl={imageUrl}
              onUploadSuccess={handleImageUploadSuccess}
              accept="image/*"
              maxCount={1}
            />
          </Form.Item>

          {/* 首页显示表单项 */}
          <Form.Item<CategoryFormValues>
            name="homeview"
            label="首页显示"
            rules={[{ required: true, message: '请选择是否首页显示' }]}
            valuePropName="checked"
          >
            <Switch
              checkedChildren="显示"
              unCheckedChildren="不显示"
            />
          </Form.Item>

          {/* 排序表单项 */}
          <Form.Item<CategoryFormValues>
            name="sort"
            label="排序"
            rules={[
              { required: true, message: '请输入排序值' }
            ]}
          >
            <Input
              placeholder="请输入排序值"
              min={0}
              max={99}
              style={{ width: '100%' }}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleNumberInput(categoryForm, 'sort', e, { supportDecimal: false })
              }
              onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleNumberInput(categoryForm, 'sort', e, { supportDecimal: false })
              }
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;